<template>
  <el-container class="main-container">
    <!-- 左侧边栏 -->
    <el-aside width="180px" class="sidebar">
      <el-container>
        <!-- Logo区域 -->
        <el-header class="logo-header">
          <el-row type="flex" align="middle">
            <el-col :span="4">
              <el-container class="logo">
                <el-icon :size="20" color="#ffffff">
                  <Lightning />
                </el-icon>
              </el-container>
            </el-col>
            <!-- 头部 一行 两列 -->
            <el-col :span="20">
              <el-text class="logo-title" size="large" tag="strong">家庭AI</el-text>
            </el-col>
          </el-row>
        </el-header>

        <!-- 新对话按钮 -->
        <el-main class="new-chat-section">
          <el-button 
            type="primary" 
            :icon="Edit"
            @click="startNewChat"
            plain
            class="new-chat-btn"
          >
            新对话
          </el-button>
        </el-main>

        <!-- 历史对话 -->
        <el-main class="history-section">
          <div class="section-title">历史对话</div>
          <el-menu
            :default-active="activeChatId.toString()"
            class="chat-history"
          >
            <el-menu-item
              v-for="chat in chatHistory"
              :key="chat.id"
              :index="chat.id.toString()"
              @click="selectChat(chat)"
              :class="{ active: chat.active }"
            >
              <i class="el-icon-chat-dot-round"></i>
              <span slot="title">{{ chat.title }}</span>
            </el-menu-item>
          </el-menu>
        </el-main>
      </el-container>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 模型选择 -->
      <el-header class="model-header">
        <el-row type="flex" justify="space-between" align="middle">
          <el-col :span="24" class="model-selector">
            <span class="model-label">模型:</span>
            <el-select 
              v-model="selectedModel" 
              size="small"
              @change="handleModelChange"
              class="model-select"
            >
              <el-option
                v-for="model in models"
                :key="model.value"
                :label="model.label"
                :value="model.value"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-header>

      <!-- 聊天对话框 -->
      <el-main class="chat-main" ref="chatContainer">
        <div class="messages-wrapper">
          <el-timeline class="chat-timeline">
            <el-timeline-item
              v-for="message in messages"
              :key="message.id"
              :timestamp="''"
              placement="top"
              :type="message.sender === 'user' ? 'primary' : ''"
              class="message-item"
              :class="message.sender"
            >
              <el-card 
                :class="['message-card', message.sender]"
                shadow="never"
              >
                <p class="message-content">{{ message.text }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
          <div ref="messagesEnd"></div>
        </div>
      </el-main>

      <!-- 输入区域 -->
      <el-footer class="input-footer">
        <el-form @submit.native.prevent="handleSendMessage">
          <el-form-item>
            <el-input
              v-model="inputMessage"
              placeholder="输入您的消息..."
              @keyup.enter.native="handleSendMessage"
              class="message-input"
            >
            <template #append>
              <el-button
                slot="append"
                icon="el-icon-s-promotion"
                @click="handleSendMessage"
                :disabled="!inputMessage.trim()"
                type="primary"
                >发送</el-button>
            </template>

            </el-input>
          </el-form-item>
        </el-form>
      </el-footer>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { Lightning,Edit } from '@element-plus/icons-vue'
import { AIChatApi,AIChatRequest, AIChatResponse } from '@/api/system/aichat' 

// --- 状态管理 ---
const messages = ref<Array<{ id: number; text: string; sender: 'user' | 'ai' }>>([
  { id: 1, text: "你好！我是AI助手，有什么我可以帮你的吗？", sender: 'ai' }
])

const inputMessage = ref('')

const selectedModel = ref('qwen3:8b') // 可选模型

const chatHistory = reactive([
  { id: 1, title: "新对话", active: true }
])

const isLoading = ref(false) // 加载状态

// --- 计算属性 ---
const activeChatId = computed(() => {
  const activeChat = chatHistory.find(chat => chat.active)
  return activeChat ? activeChat.id : 1
})

// --- 方法 ---
const scrollToBottom = () => {
  nextTick(() => {
    const el = document.getElementById('messages-end')
    if (el) el.scrollIntoView({ behavior: 'smooth' })
  })
}

const handleSendMessage = async () => {
  const currentSessionId = activeChatId.value
  const message = inputMessage.value.trim()
  
  if (!message) return
  
  // 添加用户消息
  const userMsg = {
    id: messages.value.length + 1,
    text: message,
    sender: 'user'
  }
  messages.value.push(userMsg)
  inputMessage.value = ''
  isLoading.value = true

  // 构造请求参数（支持历史）
  const history = messages.value
    .filter(msg => msg.sender !== 'ai' || msg.id > 1) // 过滤掉第一个系统欢迎语
    .map(msg => ({
      role: msg.sender === 'user' ? 'user' : 'assistant',
      content: msg.text
    }))

  const request: AIChatRequest = {
    user_message: message,
    system_prompt: "你是一个温柔贴心的AI助手，擅长倾听和鼓励。",
    history: history.length > 0 ? history : undefined,
    max_tokens: 1000,
    temperature: 0.7,
    session_id : currentSessionId
  }

  try {
    const res = await AIChatApi.generate(request)
    console.log('AI服务返回结果:', res)
    if (res.code === 200) {
      const aiResponse: AIChatResponse = res.data

      const aiMsg = {
        id: messages.value.length + 1,
        text: aiResponse.response_text,
        sender: 'ai'
      }
      messages.value.push(aiMsg)
    } else {
      throw new Error(res.message || 'AI服务返回错误')
    }
  } catch (error: any) {
    const errorMsg = {
      id: messages.value.length + 1,
      text: `抱歉，AI服务出错了：${error.message || '网络异常，请稍后再试'}`,
      sender: 'ai'
    }
    messages.value.push(errorMsg)
    console.error('AI对话失败:', error)
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

const startNewChat = () => {
  const newChat = {
    id: chatHistory.length + 1,
    title: "新对话",
    active: true
  }

  chatHistory.forEach(chat => (chat.active = false))
  chatHistory.unshift(newChat)

  messages.value = [
    { id: 1, text: "你好！我是AI助手，有什么我可以帮你的吗？", sender: 'ai' }
  ]
}

const selectChat = (chat: { id: number; title: string; active: boolean }) => {
  chatHistory.forEach(c => (c.active = c.id === chat.id))
  // TODO: 实际项目中应从服务端加载该会话的历史记录
  // 此处仅清空，实际可配合 localStorage / Redis 恢复历史
  messages.value = [
    { id: 1, text: "你好！我是AI助手，有什么我可以帮你的吗？", sender: 'ai' }
  ]
}

// --- 生命周期 ---
import { onMounted } from 'vue'
onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.main-container {
  height: 100vh;
  background-color: #f5f7fa;
}

/* 左侧边栏样式 */
.sidebar {
  background-color: white;
  border-right: 1px solid #e4e7ed;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.logo-header {
  height: 60px !important;
  line-height: 80px;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.logo {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #409EFF 0%, #1a73e8 100%);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
}

.logo-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  margin-left: 12px;
}

.new-chat-section {
  padding: 16px 20px;
}

.new-chat-btn {
  width: 100%;
}

.history-section {
  padding: 0 12px 20px;
}

.section-title {
  padding: 8px 16px;
  font-size: 12px;
  font-weight: 600;
  color: #909399;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.chat-history {
  border: none;
}

.chat-history .el-menu-item {
  height: 48px;
  line-height: 48px;
  border-radius: 6px;
  margin: 4px 0;
}

.chat-history .el-menu-item:hover {
  background-color: #ecf5ff;
}

.chat-history .el-menu-item.active {
  background-color: #ecf5ff;
  border-right: 3px solid #409EFF;
  color: #409EFF;
  font-weight: 500;
}

/* 主内容区样式 */
.model-header {
  height: 60px !important;
  line-height: 60px;
  background-color: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 24px;
}

.chat-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.model-selector {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
}

.model-label {
  font-size: 14px;
  color: #606266;
}

.model-select {
  width: 120px;
}

.chat-main {
  background-color: #f5f7fa;
  padding: 24px;
  overflow-y: auto;
}

.messages-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

.chat-timeline {
  padding: 0;
}

.message-item {
  padding-bottom: 20px;
}

.message-item.user {
  align-self: flex-end;
}

.message-item.ai {
  align-self: flex-start;
}

.message-card {
  border: none;
  background: transparent;
  margin-left: 0;
  margin-right: 0;
  display: inline-block;
  max-width: 80%;
}

.message-card.user {
  margin-left: auto;
  float: right;
}

.message-card.ai {
  margin-right: auto;
  float: left;
}

.message-card.user .message-content {
  background-color: #409EFF;
  color: white;
  border-radius: 18px;
  border-bottom-right-radius: 4px;
  padding: 12px 16px;
  margin: 0;
  display: inline-block;
  max-width: 100%;
  word-wrap: break-word;
}

.message-card.ai .message-content {
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 18px;
  border-bottom-left-radius: 4px;
  padding: 12px 16px;
  margin: 0;
  display: inline-block;
  max-width: 100%;
  word-wrap: break-word;
}

/* 清除浮动 */
.chat-timeline ::v-deep .el-timeline-item__wrapper {
  display: flex;
  flex-direction: column;
}

.chat-timeline ::v-deep .el-timeline-item__tail {
  left: 16px;
}

.input-footer {
  height: 80px !important;
  line-height: 80px;
  background-color: white;
  border-top: 1px solid #e4e7ed;
  padding: 20px 24px;
}

.message-input ::v-deep .el-input-group__append {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}

.message-input ::v-deep .el-button:disabled {
  background-color: #a0cfff;
  border-color: #a0cfff;
}
</style>